function calSet(input, img){
	Calendar.setup({
	  inputField     :    input,     // id of the input field
	  ifFormat       :    "%m/%d/%Y",      // format of the input field
	  button         :    img,  // trigger for the calendar (button ID)
	  //align          :    "Tl",           // alignment (defaults to "Bl")
	  singleClick    :    true
	});
}

function setup(){
	calSet("eventsdate", "esd_cal_trigger");
	calSet("eventedate", "eed_cal_trigger");
	calSet("edit_eventsdate", "edit_esd_cal_trigger");
	calSet("edit_eventedate", "edit_eed_cal_trigger");
}

//Global vars; can we get rid of these and make it safer!!!!
var target;
var tbox;

function getSuggestion(textBox, display, url){
	var text = textBox.value;
	target = document.getElementById(display);
	
	//global var, I need to do it better!!!!!
	tBox = textBox;
	
	//if there is no text in the box, i.e. the user has deleted the text he/she input, then we need to get rid of the list that we are left showing...
	if(text == "" || text.length < 2){
		target.style.display = 'none';
		//showSelect();
		return;
	}
	//make a request to the server for the results
	var request = new Request();
	request.setResponseType('text');
	request.setCallback(showResults);
	request.setQuerystring("mail="+text);
	request.doRequest('post', url, true);	
}

//showresults takes a string delimited by a '\n' newline that has been returned by a call to the server
//and formats it into a list
function showResults(string){
	if(string == ''){	
		//showSelect();
		return;
	}
	
	var myArray = string.split("\n");
	var list = document.createElement('ul');
	list.style.overflow = 'auto';
	count = myArray.length;
	if(myArray.length > 10){
		list.style.height = 350+'px';
	}
			
	//remove any previous entries in the list	
	while (target.childNodes.length > 0) {
               target.removeChild(target.firstChild);
	}
	
	for(var index = 0; index < count; index++){
		if(myArray[index] !=''){
			str = myArray[index].split("\|");
		  var lItem = document.createElement('li');
		  var a = document.createElement('a');
		  var text = document.createTextNode(str[1]);
			a.appendChild(text);
			a.onclick = function(){selectName(this)};
		  a.setAttribute("href","#");
			
		  lItem.appendChild(a);
			list.appendChild(lItem);
		}
	}

		lItem = document.createElement('li');
		var a = document.createElement('a');
		
		a.style.background = 'url(images/bottom.gif) no-repeat';
		a.style.borderBottom = 0+'px';
		lItem.appendChild(a)
		list.appendChild(lItem);
	
	target.appendChild(list);
	target.style.display = 'block';
	target.style.position = 'absolute';
}

function selectName(name){
	tBox.value = name.firstChild.nodeValue;
	addMail(tBox);
	target.style.display = 'none';
}

function addMail(id){
	if(id.value != ''){
		var list = document.getElementById('memList');
		var box = document.createElement('input');
		box.type = "checkbox";
		box.checked  = 'true';
		var lItem = document.createElement('li');
		var txt  = document.createTextNode(id.value);
		
		lItem.appendChild(box);
		lItem.appendChild(txt);
		
		var select = document.createElement("select");
		select.name = "permissions";
		select.style.fontSize = "8pt";
		select.style.marginLeft = "20px"
		var option = document.createElement("option");
		txt = document.createTextNode("Read Only");
		option.value = "read";
		option.appendChild(txt);
		select.appendChild(option);
		
		option = document.createElement("option");
		txt = document.createTextNode("Show Free or Busy Status Only");
		option.value = "freebusy";
		option.appendChild(txt);
		select.appendChild(option);
		
		option = document.createElement("option");
		txt = document.createTextNode("Full Access");
		option.value = "editor";
		option.appendChild(txt);
		select.appendChild(option);
		
		lItem.appendChild(select);
		list.appendChild(lItem);
		list.parentNode.style.display = 'block';
		
		id.value = '';
	}
}

//createTeam sends info to the server script to create a new team in the database if one does not already exist
//in addition to creating a new shared calendar with this team name
function createTeam(elem){
	var docBody = document.getElementsByTagName('body')[0];
	var form = document.getElementById(elem);
	var content = form.parentNode.parentNode;
	var ctDiv = form.parentNode;
	var teamname = document.getElementById("teamname").value;
	var members = getChecked("memList");
	var color = document.getElementById("teamCalendarColor").value;
	
	if(members == ""){
		alert("You must select members for your team!");
		return;
	}
	if(teamname == ""){
		alert("You must select a team name!");
		return;
	}
	var img;
	var request = new Request();
	request.setResponseType('text');
	request.setCallback(function(response){
		if(response == "0"){
			alert("Your attempt to create a new team was unsuccessful, please try again.");
		}else if(response == "1"){
			cancel(resetCreateTeamForm);
			addDynamicCal(teamname,color);
			alert("You have successfully created a new team!");
		}else if(response == "2"){
			alert("The team name exists, please try another name!");
		}else 	alert("Your attempt to create a new team was unsuccessful, please try again.");//alert(response);
											});
	request.setQuerystring("members="+ members+"&teamname="+teamname);
	request.doRequest('post', 'createTm.php', true);
}

function getChecked(elem){
	var boxes = document.getElementById(elem).getElementsByTagName("input");
	var rtn = "";
	for(var index = 0; index < boxes.length; index++){
		if(boxes[index].checked){
			rtn += boxes[index].nextSibling.nodeValue + ":" + boxes[index].nextSibling.nextSibling.value + "|";
		}
	}
	return rtn;
}

//resetCreateTeamForm is used to clear the form values in the createTeam form
function resetCreateTeamForm(){
	//clear the teamname field
	document.getElementById("teamname").value = "";
	//clear any text in the invitemem field
	document.getElementById("invitemem").value = "";
	var memList =  document.getElementById("memList");
	//remove any previous entries in the list	
	while (memList.childNodes.length > 0) {
  	memList.removeChild(memList.firstChild);
	}
	memList.parentNode.style.display = "none";
}

/****************NEED TO REFACTOR THE TWO FUNCTINS BELOW INTO ONE**********************/
//resetAddEventForm is used to clear the form values in the addEvent form
function resetAddEventForm(){
	//
	document.getElementById("eventname").value = "";
	document.getElementById("eventloc").value = "";
	document.getElementById("eventdesc").innerHTML = "";
	document.getElementById("eventdesc").value = "";
	//
	document.getElementById("eventsdate").value = "mm/dd/yyyy";
	document.getElementById("eventedate").value = "mm/dd/yyyy";
	document.getElementById("eventstime").value = "hh:mm a/pm";
	document.getElementById("eventetime").value = "hh:mm a/pm";
	//make sure they are still visible
	document.getElementById("to").display = "inline";
	document.getElementById("eventedate").display = "inline";
	document.getElementById("eventstime").display = "inline";
	document.getElementById("eventetime").display = "inline";
	document.getElementById("eed_cal_trigger").display = "inline";
	
	
}

function resetEditEventForm(){
	//
	document.getElementById("edit_eventname").value = "";
	document.getElementById("edit_eventloc").value = "";
	document.getElementById("edit_eventdesc").innerHTML = "";
	document.getElementById("edit_eventdesc").value = "";
	//
	document.getElementById("edit_eventsdate").value = "mm/dd/yyyy";
	document.getElementById("edit_eventedate").value = "mm/dd/yyyy";
	document.getElementById("edit_eventstime").value = "hh:mm a/pm";
	document.getElementById("edit_eventetime").value = "hh:mm a/pm";
	//make sure they are still visible
	document.getElementById("edit_to").display = "inline";
	document.getElementById("edit_eventedate").display = "inline";
	document.getElementById("edit_eventstime").display = "inline";
	document.getElementById("edit_eventetime").display = "inline";
	document.getElementById("edit_eed_cal_trigger").display = "inline";
	
	
}

/*!!!!!!!!!REFACTOREFACTOREFACTOREFACTOREFACTOREFACTOREFACTOREFACTOREFACTOREFACTOREFACTOREFACTOR!!!!!!!!*/

//the cancel function is used with a reset function to close the popup box via a button other than the close img
//the function simple resets the form, closees the popup box and brings the body back into full focus
function cancel(reset){
	var wrapper = document.getElementById("fadewrapper");
	//close the popup box and bring the body back into focus
	var docBody = document.getElementsByTagName("body")[0];
	wrapper.style.opacity = 1;
	wrapper.style.filter = 'alpha(opacity=' + 100 + ')'; 
	document.getElementById("popup").style.display = "none";
	//reset the popup elems
	reset();
}

function wipe(elem, defaultVal){
	if(elem.value == defaultVal){
		elem.value = "";
	}
}

function dateIsValid(date, defaultVal){
	if(!isValidDate(date.value, "mm/dd/yyyy") && date.value != ""){
		date.style.border = "1px solid red";
	}else{
		date.style.border = "";
		var endDate = document.getElementById("eventedate");
		if(date.id == "eventsdate" && date.value != "" && endDate.value == defaultVal){
			endDate.value = date.value;
		}
	}
	
	if(date.value == "")
		date.value = defaultVal;
}

function oneBeforeOther(startdate, enddate, starttime, endtime){
    var startyear;
    var startmonth;
    var startday;
    var startdate_parts = null;
    var endyear;
    var endmonth;
    var endday;
    var enddate_parts = null;
    var rtrn = true;
    var format="mm/dd/yyyy";
    if (/^m{1}[./-]d{1}[./-]y{1}$/.test(format)) {
        //US Date
        startdate_parts = startdate.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{2}|\d{4})$/);
        enddate_parts = enddate.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{2}|\d{4})$/);
        if (startdate_parts && enddate_parts) {
            startmonth = startdate_parts[1];
            startday = startdate_parts[2];
            startyear = startdate_parts[3];
            endmonth = enddate_parts[1];
            endday = enddate_parts[2];
            endyear = enddate_parts[3];
        }
    } else if (/^m{2}[./-]d{2}[./-]y{2}$/.test(format)) {
        //US Short Date
        startdate_parts = startdate.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{2})$/);
        enddate_parts = enddate.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{2})$/);
        if (startdate_parts && enddate_parts) {
            startmonth = startdate_parts[1];
            startday = startdate_parts[2];
            startyear = startdate_parts[3];
            endmonth = date_parts[1];
            endday = enddate_parts[2];
            endyear = enddate_parts[3];
        }
    } else if (/^m{2}[./-]d{2}[./-]y{4}$/.test(format)) {
        //US Long Date
        startdate_parts = startdate.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/);
        enddate_parts = enddate.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/);
        if (startdate_parts && enddate_parts) {
            startmonth = startdate_parts[1];
            startday = startdate_parts[2];
            startyear = startdate_parts[3];
            endmonth = enddate_parts[1];
            endday = enddate_parts[2];
            endyear = enddate_parts[3];
        }
    } else if (/^y{1}[./-]m{1}[./-]d{1}$/.test(format)) {
        //EU Date
        startdate_parts = startdate.match(/^(\d{2}|\d{4})[./-](\d{1,2})[./-](\d{1,2})$/);
        enddate_parts = enddate.match(/^(\d{2}|\d{4})[./-](\d{1,2})[./-](\d{1,2})$/);
        if (startdate_parts && enddate_parts) {
            startyear = startdate_parts[1];
            startmonth = startdate_parts[2];
            startday = startdate_parts[3];
            endyear = enddate_parts[1];
            endmonth = enddate_parts[2];
            endday = enddate_parts[3];
        }
    } else if (/^y{2}[./-]m{2}[./-]d{2}/.test(format)) {
        //EU Short Date
        startdate_parts = startdate.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{1,2})$/);
        enddate_parts = enddate.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{1,2})$/);
        if (startdate_parts && enddate_parts) {
            startyear = startdate_parts[1];
            startmonth = startdate_parts[2];
            startday = startdate_parts[3];
            endyear = enddate_parts[1];
            endmonth = enddate_parts[2];
            endday = enddate_parts[3];
        }
    } else if (/^y{4}[./-]m{2}[./-]d{2}/.test(format)) {
        //EU Long Date
        startdate_parts = startdate_string.match(/^(\d{4})[./-](\d{1,2})[./-](\d{1,2})$/);
        enddate_parts = enddate_string.match(/^(\d{4})[./-](\d{1,2})[./-](\d{1,2})$/);
        if (startdate_parts && enddate_parts) {
            startyear = startdate_parts[1];
            startmonth = startdate_parts[2];
            startday = startdate_parts[3];
            endyear = enddate_parts[1];
            endmonth = enddate_parts[2];
            endday = enddate_parts[3];
        }
    } else {
    	alert("Please enter a valid date");
        return false;
    }


	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

	var startMatchArray = startTimeStr.match(timePat);
	var endMatchArray = endTimeStr.match(timePat);

	if (startMatchArray == null || endMatchArray == null) {
		return false;
		alert("Please enter a valid date");
	}


	starthour = startMatchArray[1];
	startminute = startMatchArray[2];
	startsecond = startMatchArray[4];
	startampm = startMatchArray[6];

	endhour = endMatchArray[1];
	endminute = endMatchArray[2];
	endsecond = endMatchArray[4];
	endampm = endMatchArray[6];

	if (startdate_parts && enddate_parts) {
		if (endyear<startyear || ((endyear == startyear) && endmonth<startmonth) || (endyear==startyear && endmonth==startmonth && endday<startday) || 
			(endyear==startyear && endmonth==startmonth && endday==startday && endhour<starthour && endampm==startampm) || 
				(endyear==startyear && endmonth==startmonth && endday==startday && endhour==starthour && endampm==startampm && endminute<startminute) ||
					(endyear==startyear && endmonth==startmonth && endday==startday && endhour==starthour && endampm==startampm &&
						endminute==startminue && endsecond<startsecond)){
							alert("Please ensure start time is before end time");
							rtrn = false;
		}	
    	}
    
    return rtrn;
}


/*
http://lawrence.ecorp.net/inet/samples/regexp-validate.php
ACCEPTED FORMATS:
 US Date (m/d/y)
 US Short Date (mm/dd/yy)
 US Long Date (mm/dd/yyyy)
 EU Date (y/m/d)
 EU Short Date (yy/mm/dd)
 EU Long Date (yyyy/mm/dd)
*/
function isValidDate(date_string) {
		format = "mm/dd/yyyy";
    var days = [31,28,31,30,31,30,31,31,30,31,30,31];
    var year;
    var month;
    var day;
    var date_parts = null;
    var rtrn = true;

    if (/^m{1}[./-]d{1}[./-]y{1}$/.test(format)) {
        //US Date
        date_parts = date_string.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{2}|\d{4})$/);
        if (date_parts) {
            month = date_parts[1];
            day = date_parts[2];
            year = date_parts[3];
        }
    } else if (/^m{2}[./-]d{2}[./-]y{2}$/.test(format)) {
        //US Short Date
        date_parts = date_string.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{2})$/);
        if (date_parts) {
            month = date_parts[1];
            day = date_parts[2];
            year = date_parts[3];
        }
    } else if (/^m{2}[./-]d{2}[./-]y{4}$/.test(format)) {
        //US Long Date
        date_parts = date_string.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/);
        if (date_parts) {
            month = date_parts[1];
            day = date_parts[2];
            year = date_parts[3];
        }
    } else if (/^y{1}[./-]m{1}[./-]d{1}$/.test(format)) {
        //EU Date
        date_parts = date_string.match(/^(\d{2}|\d{4})[./-](\d{1,2})[./-](\d{1,2})$/);
        if (date_parts) {
            year = date_parts[1];
            month = date_parts[2];
            day = date_parts[3];
        }
    } else if (/^y{2}[./-]m{2}[./-]d{2}/.test(format)) {
        //EU Short Date
        date_parts = date_string.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{1,2})$/);
        if (date_parts) {
            year = date_parts[1];
            month = date_parts[2];
            day = date_parts[3];
        }
    } else if (/^y{4}[./-]m{2}[./-]d{2}/.test(format)) {
        //EU Long Date
        date_parts = date_string.match(/^(\d{4})[./-](\d{1,2})[./-](\d{1,2})$/);
        if (date_parts) {
            year = date_parts[1];
            month = date_parts[2];
            day = date_parts[3];
        }
    } else {
        rtrn = false;
    }
    if (date_parts) {
        if (1 <= month && month <= 12) {
            if (month == 2) {
                if (year % 4 != 0 ? false : ( year % 100 != 0? true: (year % 1000 != 0? false : true))) {
                    rtrn = (1 <= day && day <= 29);
                } else {
                    rtrn = (1 <= day && day <= 28);
                }
            } else {
                rtrn = (1 <= day && day <= days[month -1]);
            }
        }else {
            rtrn = false;
        }
    } else {
        rtrn = false;
    }
    return rtrn;
}

function timeIsValid(time, defaultVal){
	if(!isValidTime(time.value) && time.value != ""){
		time.style.border = "1px solid red";
	}else{
		time.style.border = "";
	}
	
	if(time.value == "")
		time.value = defaultVal;
} 

//<!-- Original:  Sandeep Tamhankar (stamhankar@hotmail.com) -->
//<!-- Web Site:  http://207.20.242.93 -->

function isValidTime(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
return false;
}
if  (hour > 12 && ampm != null) {
return false;
}
if (minute<0 || minute > 59) {
return false;
}
if (second != null && (second < 0 || second > 59)) {
return false;
}
return true;
}

function eventIsValid(){
	if(document.getElementById("eventname").value == ""){
		alert("You must have an event title!");
		return false;
	}
	var eDate = document.getElementById("eventedate").value;
	var sDate = document.getElementById("eventsdate").value;
	
	if(!document.getElementById("allDay").checked && (!isValidTime(document.getElementById("eventstime").value)  ||  !isValidTime(document.getElementById("eventetime").value))){
		alert("Please make sure you have entered a correct time in the format hh:mm a/pm.");
		return false;
	}
	if(!isValidDate(eDate) || (!document.getElementById("allDay").checked && !isValidDate(sDate))){
		alert("Please make sure you have entered a correct date in the format mm/dd/yyyy");
		return false;
	}
	if(isGreaterDate(sDate, eDate && !document.getElementById("allDay").checked)){
		alert("You can not create an event that ends before it starts!");
		return false;
	}
	/*if(!isValidTime(!document.getElementById("allDay").value && (document.getElementById("eventstime").value)  || !isValidTime(document.getElementById("eventetime").value))){
		alert("Please make sure you have entered a correct time in the format hh:mm a/pm.");
		return false;
	} 
	if(!isValidDate(document.getElementById("eventsdate").value)  || !isValidDate(document.getElementById("eventedate").value) || !oneBeforeOther(document.getElementById("eventsdate").value, document.getElementById("eventedate").value)){
		alert("Please make sure you have entered a correct date in the format mm/dd/yyyy");
		return false;
	}*/
	return false;
}

function isGreaterTime(time1, time2){
	
	return time_1 > time_2;
}
function isGreaterDate(date1, date2, time1, time2){
	//time1.split("");
	var date_1 = new Date(date1);
	var date_2 = new Date(date2);
	return date_1 > date_2;
}

function toggleTarget(control, target){
		
		if ($("#"+control).is(":checked")){
    	//show the hidden target
    	$("#"+target).show("fast");
			$("#"+target).css({ display:"inline"});
  	}
  	else{     
  		//otherwise, hide it
    	$("#"+target).hide("fast");
			
  	}
}

function toggleTargetR(control, targets){
		
		if ($("#"+control).is(":checked")){
    	//hide it
			for(var i = 0; i < targets.length; i++){
    		$("#"+targets[i]).css({ display:"none"});
			}
  	}
  	else{     
			//show the hidden target
			for(var i = 0; i < targets.length; i++){
				$("#"+targets[i]).css({ display:"inline"});
			}
  	}
}

function toggleEvents(control, classname){
	var targets = document.getElementsByTagName("li");
	if ($(control).is(":checked")){
  	//show the hidden target
		for(var i = 0; i < targets.length; i++){
			if(targets[i].className == classname){
				$(targets[i]).css({ display:"block"});
			}
		}
	}
	else{     
		//hide
		for(var i = 0; i < targets.length; i++){
			if(targets[i].className == classname){
  			$(targets[i]).css({ display:"none"});
			}
		}
	}
}

function editEvent(ev){//alert(ev.eid);
	if(ev.id)
		document.getElementById("edit_eventid").value = ev.id;
	if(ev.name)
		document.getElementById("edit_eventname").value = ev.name;
	if(ev.startTime)
		document.getElementById("edit_eventstime").value = makeTime(ev.startTime);
	if(ev.endTime)
		document.getElementById("edit_eventetime").value = makeTime(ev.endTime);		
	if(ev.startDate)
		document.getElementById("edit_eventsdate").value = ev.startDate;
	if(ev.endDate)
		document.getElementById("edit_eventedate").value = ev.endDate;				
	if(ev.place)
		document.getElementById("edit_eventloc").value = ev.place;
	if(ev.desc)
		document.getElementById("edit_eventdesc").innerHTML = ev.desc;
	if(ev.eid)
		document.getElementById("eid").value = ev.eid;			

	var cont = document.getElementById("editEvent");
	new Popup(cont, resetEditEventForm, 'createEvent');
	cont.style.display = "block";
}

function makeTime(time){
	var mytime = time.split(":");
	var hr = mytime[0];
	var min = mytime[1];
	var meridian = "am";
	var rtn = "";
	if(hr == 0){
		hr = 12;
	}else if(hr > 12){
		hr = hr - 12;
		meridian = "pm";
	}else if(hr < 10){
		hr = "0"+hr;
	}
	if(hr == 12)
		meridian = "pm";
	if(min == 0)
		min = "00";
	return hr+":"+min+" "+meridian;	
}

function addDynamicCal(title, color){

	var calList = document.getElementById("calList");
	var li = document.createElement("li");
	var iput = document.createElement("input");
	var txt = document.createTextNode(title);
	li.style.backgroundColor = color;
	li.style.color = "#fff";
	iput.type = "checkbox";
	iput.onClick = function(){toggleEvents(this, color);};
	iput.checked = true;
	li.style.opacity = .85;
	li.style.filter = 'alpha(opacity=' + 85 + ')';
	li.appendChild(iput);
	li.appendChild(txt);
	calList.appendChild(li);
	
}
